package com.garen.projects.demo.provider.handler;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author garen
 */
@RestController
@RequestMapping("/discovery")
public class DiscoveryController {

    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/instance")
    public List<String> instances() {
        List<String> resultInfos = new ArrayList<>();
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            List<ServiceInstance> instances = discoveryClient.getInstances(service);
            for (ServiceInstance instance : instances) {
                String resultInfo = service + "    " + instance.getInstanceId() + "    " + instance.getHost() + "    " + instance.getPort();
                resultInfos.add(resultInfo);
            }
        }
        return resultInfos;
    }
}
